package net.wanho.filter;

import cn.hutool.json.JSONUtil;
import net.wanho.properties.IgnoreWhiteProperties;
import net.wanho.vo.AjaxResult;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 实现统一的身份校验
 */
// @Component
public class AuthFilter implements GlobalFilter, Ordered{

    @Resource
    private IgnoreWhiteProperties ignoreWhite;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("LoginGatewayFilter.filter..........................");

        // 跳转不需要校验的url
        String url = exchange.getRequest().getURI().getPath();
        if (ignoreWhite.getWhites().contains(url)){
            return chain.filter(exchange); // 放行
        }

        /**
         * 判断token是否存在
         */
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if(StringUtils.isEmpty(token)){
            ServerHttpResponse res = exchange.getResponse();
            String jsonStr = JSONUtil.toJsonStr(AjaxResult.error("请先登录再操作"));
            DataBuffer dataBuffer = res.bufferFactory().wrap(jsonStr.getBytes(StandardCharsets.UTF_8));

            res.setStatusCode(HttpStatus.UNAUTHORIZED); // 设置响应状态码
            res.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
            return res.writeWith(Mono.just(dataBuffer)); // 设置响应内容
        }

        /**
         * 校验token是否合法
         */

        return chain.filter(exchange); // 放行
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
